package legumes.client.ui.top;

import java.util.ArrayList;
import java.util.List;

import legumes.client.evt.customer.CustomerStoreSelectionChangedEvent;
import legumes.client.evt.manager.EventBusManager;
import legumes.client.evt.store.StoreRemovedEvent;
import legumes.client.evt.store.StoreRemovedEventHandler;
import legumes.client.resources.PNResources;
import legumes.client.services.callbacks.AddStoreCallback;
import legumes.client.services.callbacks.GetUserStoresCallback;
import legumes.client.services.callbacks.IsStoreNameExistsCallback;
import legumes.client.services.util.rpc.RPCCallSequencer;
import legumes.client.ui.Authentication;
import legumes.client.ui.widgets.list.ComboOrderedListWidget;
import legumes.shared.domain.Store;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Widget;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.util.ValueCallback;
import com.smartgwt.client.widgets.Dialog;

public class MyStoreListWidget extends ComboOrderedListWidget {

	public MyStoreListWidget(){
		super();
		bind();
	}

	private void bind(){
		EventBusManager.getInstance().getEventBus().addHandler(
				StoreRemovedEvent.TYPE, 
				new StoreRemovedEventHandler(){

					@Override
					public void onStoreRemoved(StoreRemovedEvent event) {
						reloadData();
					}
				});
	}
	
	
	private Anchor createAnchorMenuItem(String itemTxt_, final Command cmd_){
		final Anchor anchor = new Anchor(itemTxt_);
		anchor.setStyleName("menuItemsCombo");
		anchor.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				cmd_.execute();
			}
		});
		return anchor;
	}
	
	public void reloadData(){
		RPCCallSequencer callSequencer = new RPCCallSequencer();
		final GetUserStoresCallback getUserStoresCallback = new GetUserStoresCallback(
				Authentication.getCustomer().getEmail() );
		callSequencer.addCall(getUserStoresCallback);
		callSequencer.addRunnable(new Runnable() {
			public void run() {
				onStoreListChanged( getUserStoresCallback.getStoreList() );
			}
		});
	
		callSequencer.callSequence();
	}

	protected void onStoreListChanged(List<Store> storeList_) {
		List<Widget> menuItemList = new ArrayList<Widget>();
		for(final Store st : storeList_){
			
			Widget storeWidget = createAnchorMenuItem(st.getStoreName(), new Command() {
				
				@Override
				public void execute() {
					doStoreSelectedAction(st);
				}
			});
			menuItemList.add( storeWidget );
			
		}
		
		String titleNewStore;
		if(storeList_.size()<0){
			titleNewStore = "Créer votre magasin en 3 étapes...";
		} else {
			titleNewStore = "Ajouter un nouveau magasin...";
		}
		Widget storeWidget = createAnchorMenuItem(titleNewStore, new Command() {
			
			@Override
			public void execute() {
				createNewStore();
			}
		});
		menuItemList.add( storeWidget );
		
		setMenu(menuItemList, true);
	}

	protected void createNewStore() {
		Dialog dg = new Dialog();
		dg.setShowModalMask(true);
		dg.setWidth(400);
		SC.askforValue("<img src=\"" + PNResources.INSTANCE.addIcon().getURL() + "\" />&nbsp;Nouveau magasin", 
				"Saisir le nom de votre magasin <i>(Exemple : Les bons produits du terroir)</i> : ", 
				"",
				new ValueCallback() {
					
					@Override
					public void execute(final String value) {
						if( value != null && value.trim().length()>0){
							//Check store name do not already exists
							RPCCallSequencer callSequencer = new RPCCallSequencer();
							final IsStoreNameExistsCallback checkStoreNameCallback = new IsStoreNameExistsCallback(value);
							callSequencer.addCall(checkStoreNameCallback);
							callSequencer.addRunnable(new Runnable() {
								public void run() {
									if( checkStoreNameCallback.isStoreExists() ){
										SC.say("Nom déjà existant", "Le nom de magasin '" + value + "' existe déjà. Veuillez saisir un nouveau nom.", new BooleanCallback() {
											
											@Override
											public void execute(Boolean value) {
												createNewStore();
											}
										});
									} else {
										createNewStore(value);
									}
								}
							});
							callSequencer.callSequence();
						}
					}
				},
				dg);
	}
	
	private void createNewStore(final String storeName_){
		RPCCallSequencer callSequencer = new RPCCallSequencer();
		Store stToCreate = new Store();
		//stToCreate ID is created on the serveur
		stToCreate.setCustomerId(Authentication.getCustomer().getEmail());
		stToCreate.setOpened(false);
		stToCreate.setStoreName(storeName_);
		stToCreate.setMessage("");
		
		final AddStoreCallback addStoreCallback = new AddStoreCallback(stToCreate);
		callSequencer.addCall(addStoreCallback);
		callSequencer.addRunnable(new Runnable() {
			
			@Override
			public void run() {
				Store addedStore = addStoreCallback.getAddedStore();
				if(addedStore!=null){
					reloadData();
					doStoreSelectedAction(addedStore);
				}
			}
		});
		callSequencer.callSequence();
	}

	private void doStoreSelectedAction(Store store_) {
		EventBusManager.getInstance().getEventBus().fireEvent(
				new CustomerStoreSelectionChangedEvent(store_) );
	}
}
